package code15.io;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

public class TestGame {

	public static void main(String[] args) {
		TestGame tg = new TestGame();
		tg.show();
	}
	
	JFrame jt;
	JButton newBtn;
	JButton continueBtn;
	
	public void show() {
		init();
		bindEvent();
	}
	private void init() {
		jt = new JFrame("RPG");
		jt.setLayout(null);
		jt.setSize(300, 400);
		jt.setResizable(false);
		jt.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jt.setLocationRelativeTo(null);
		
		newBtn = new JButton("new Game");
		newBtn.setBounds(100, 200, 100, 30);
		jt.add(newBtn);
		
		continueBtn = new JButton("continue");
		continueBtn.setBounds(100, 240, 100, 30);
		jt.add(continueBtn);
		
		jt.setVisible(true);
	}
	private void bindEvent() {
		newBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				saveData();
			}
		});
		continueBtn.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				loadData();
			}
		});
	}
	private void saveData() {
		// 创建初始角色对象, 并保存到指定位置
		Player p = new Player(1, "neo", 50, 40, 30, 60, 0);
		try (
				ObjectOutputStream oos = new ObjectOutputStream(
						new FileOutputStream("player.data"));
				) {
			oos.writeObject(p);
			// 把对象的信息调用 showMsg 显示
			showMsg(p.toString());
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	private void loadData() {
		// 读取存档, 取出角色对象
		try (
				ObjectInputStream ois = new ObjectInputStream(
						new FileInputStream("player.data"));
				) {
			Player p = (Player) ois.readObject();
			// 把对象的信息调用 showMsg 显示
			showMsg(p.toString());
		} catch (FileNotFoundException e) {
			showMsg("没有存档, 无法继续上一次的游戏");
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		
	}
	private void showMsg(String msg) {
		JOptionPane.showMessageDialog(jt, msg, "tip", JOptionPane.INFORMATION_MESSAGE);
	}
}
